﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Text;

namespace DataAccessLayer.Models
{
    public interface IUserRepository
    {
        IQueryable<User> FindAllUsers();
        User GetUser(string username, string password);
        User GetUser(int userid);
        void Save();
    }

    public class UserRepository : IUserRepository
    {
        private LOSEntities db = new LOSEntities();

        //Query Methods
        public IQueryable<User> FindAllUsers()
        {
            return db.Users;
        }

        //Query Methods
        public virtual User GetUser(string username, string password)
        {
            string aPassword = EncodePassword(password);
            return db.Users.SingleOrDefault(d => d.UserName == username && d.UserPassword == aPassword);
        }

        //Query Methods
        public virtual User GetUser(int userid)
        {
            return db.Users.SingleOrDefault(d => d.UserId == userid);
        }

        //Persistence
        public virtual void Save()
        {
            db.SaveChanges();
        }

        private string EncodePassword(string password)
        {
            HashAlgorithm mhash = new SHA1CryptoServiceProvider();
            byte[] bytValue = Encoding.Unicode.GetBytes(password);
            byte[] bytHash = mhash.ComputeHash(bytValue);
            mhash.Clear();
            return Convert.ToBase64String(bytHash);
        }

    }
}